package org.opentcs.kernel.extensions.servicewebapi.jjwc;

import jakarta.inject.Inject;
import java.io.IOException;
import jjwc_fsy.HttpManager;
import org.opentcs.kernel.extensions.WebResult;
import org.opentcs.kernel.extensions.servicewebapi.jjwc.rxx.RXXMapConversion;

/**
 * process the request for map
 */
public class MapHandler {

  private RXXMapConversion rxxMapConversion = new RXXMapConversion();

  @Inject
  public MapHandler() {

  }

  /**
   * get data of map from ip
   *
   * @param ip:
   * @param port:
   * @return String(json)
   */
  public String getMapFromIP(String ip, Integer port) {
    //这里需要先去请求一下小车的地图获取程序，然后进行解析地图并把地图存在编辑模式下的data下
    String jsonData = sendGetRequest(ip, port);
    if (jsonData == null) {
      return WebResult.error("request failed,please contact IT");
    }
    if (rxxMapConversion.convert(jsonData,ip)) {
      return WebResult.success("get map and convert success");
    }
    return WebResult.error("get map success but convert failed");
  }

  /**
   * send get map request to vehicle
   *
   * @param ip
   * @param port
   * @return if an exception occurs, return null
   */
  private String sendGetRequest(String ip, Integer port) {
    String path = rxxMapConversion.getMapRequestPath();
    String requestData = "{\"data\":{" +
                         "\"mapcode\":\"123\"}}";
    try {
      return HttpManager.sendRequestByPostAndClose(ip,port,path,requestData);
    }
    catch (IOException e) {
      e.printStackTrace();
      return null;
    }
  }
}
